package com.wtone.platform.gat.images.gat.service.impl;

import com.wtone.platform.gat.images.gat.core.Constants;
import com.wtone.platform.gat.images.gat.core.Response;
import com.wtone.platform.gat.images.gat.entity.SubscribeDB;
import com.wtone.platform.gat.images.gat.mapper.SubscribeMapper;
import com.wtone.platform.gat.images.gat.model.*;
import com.wtone.platform.gat.images.gat.service.SubscribesService;
import com.wtone.platform.gat.images.gat.utils.BenUtils;
import com.wtone.platform.gat.images.gat.utils.DateUtils;
import com.wtone.platform.gat.images.gat.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: aiLin
 * @Date: 2020/9/27 11:36
 * @desc: 发布订阅接口实现
 */
@Slf4j
@Service
public class SubscribesServiceImpl implements SubscribesService {

    @Autowired
    HttpServletRequest request;

    @Autowired
    private SubscribeMapper subscribeMapper;


    //视图库编号 -临时性给海康使用
    @Value("${digests.DeviceID}")
    private String deviceID;


    /***
     * 订阅接口 （提供给上级订阅）
     * @param subscribeListObject 订阅者对象
     * @return
     */
    @Override
    public ResponseStatusListModeObject subscribes(SubscribeListObject subscribeListObject) {
        String reqUrl = "/VIID/Subscribes";
        List<ResponseStatus> resp3 = new ArrayList<ResponseStatus>();
        String subscribeID = request.getHeader(Constants.REQTOKEN);
        SubscribeObject subscribeObject = subscribeListObject.getSubscribeObject();
        List<Subscribe> subscribeList = subscribeObject.getSubscribeList();

        if(subscribeList==null || subscribeList.size()<=0){
            return Response.error(subscribeID,reqUrl, Constants.JSONREQ);
        }

        if(subscribeList!=null && subscribeList.size()>0){
            for(int i=0;i<subscribeList.size();i++){
                Subscribe subscribe = subscribeList.get(i);
                ResponseStatus r = new ResponseStatus();
                //订阅标识符
                try {
                    subscribe.setSubscribeStatus(0);//订阅中
                    if(StringUtils.isEmpty(subscribe.getSubscribeID()) ||StringUtils.isEmpty(subscribe.getApplicantName()) || StringUtils.isEmpty(subscribe.getApplicantOrg()) || StringUtils.isEmpty(subscribe.getReceiveAddr())){
                        return Response.error(subscribeID,reqUrl,Constants.OPERATION,"必填传递异常，请检查参数");
                    }
                    //1.存入DB然后同步redis
                    SubscribeDB subscribeDB = (SubscribeDB)BenUtils.beanTobeanLowerCase(subscribeList.get(i), SubscribeDB.class);
                    subscribeDB.setCreateBy("admin");
                    subscribeDB.setRemark(DateUtils.getDate()+"订阅加入");
                    subscribeDB.setCreateTime(DateUtils.getNowDate());
                    //2.根据订阅id 判断是否已经存在
                    List<SubscribeDB> subscribeDBS = subscribeMapper.selectSubscribeObj(subscribeDB);
                    if(subscribeDBS!=null && subscribeDBS.size()>0){
                        log.info("订阅：{}，已存在执行修改",subscribeDB.getSubscribeid());
                        if(StringUtils.isEmpty(subscribeDB.getSubscribeid()) ||StringUtils.isEmpty(subscribeDB.getApplicantname()) || StringUtils.isEmpty(subscribeDB.getApplicantorg()) || StringUtils.isEmpty(subscribeDB.getReceiveaddr())){
                            log.info("参数：{}，异常，略过修改",subscribeDB.getSubscribeid());
                        }
                        subscribeDB.setUpdateBy(subscribeDB.getApplicantname());
                        subscribeDB.setUpdateTime(DateUtils.getNowDate());
                        subscribeDB.setRemark(subscribeDB.getRemark()+","+DateUtils.getDate()+"订阅修改");
                        int mark = subscribeMapper.updateSubscribe(subscribeDB);
                        if(mark>=1){
                            r = Response.getResponOk(subscribe.getSubscribeID(),reqUrl,"修改订阅成功");
                        }else{
                            r = Response.getResponOk(subscribe.getSubscribeID(),reqUrl,"修改订阅失败");
                        }
                    }else{
                        log.info("新的订阅消息：{}，执行加入",subscribeDB.getSubscribeid());
                        int mark = subscribeMapper.insertSubscribe(subscribeDB);
                        if(mark>=1){
                            r = Response.getResponOk(subscribe.getSubscribeID(),reqUrl,"加入订阅成功");
                        }else{
                            r = Response.getResponOk(subscribe.getSubscribeID(),reqUrl,"加入订阅失败");
                        }
                    }
                }catch (Exception e){
                    r = Response.getResponOk(subscribe.getSubscribeID(),reqUrl,"订阅失败"+e.toString());
                }
                resp3.add(r);
            }
        }
        return Response.ok(resp3);
    }



    /***
     * 取消订阅（订阅标识符Id）
     * @param SubscribeID
     * @param subscribeNotific
     * @return
     */
    @Override
    public ResponseStatusObject cancelSubscribeID(String SubscribeID, SubscribeObjects subscribeNotific) {
        String reqUrl = "/VIID/Subscribes/{SubscribeID}";
        if(StringUtils.isEmpty(SubscribeID)){
            return Response.errorMsg(SubscribeID,reqUrl,"订阅标识符Id,传递不能为空");
        }
        if(subscribeNotific==null){
            return Response.errorMsg(SubscribeID,reqUrl,"取消订阅信息对象，传入不能为空");
        }

        Subscribe subscribe = subscribeNotific.getSubscribe();
        SubscribeDB subscribeDBQuery = null;
        try {
            subscribeDBQuery = (SubscribeDB) BenUtils.beanTobeanLowerCase(subscribe, SubscribeDB.class);
            subscribeDBQuery.setSubscribeid(SubscribeID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //1.根据订阅id 判断是否已经存在
        List<SubscribeDB> subscribeDBS = subscribeMapper.selectSubscribeObj(subscribeDBQuery);
        if(subscribeDBS==null || subscribeDBS.size()<=0){
            return Response.errorMsg(SubscribeID,reqUrl,"订阅标识"+SubscribeID+"不存在,取消订阅失败");
        }
        SubscribeDB s = subscribeDBQuery;
        try {
            if(StringUtils.isEmpty(s.getSubscribecancelorg()) || StringUtils.isEmpty(s.getSubscribecancelperson()) || StringUtils.isEmpty(s.getCancelreson()) || StringUtils.isEmpty(s.getCanceltime())){
                return Response.errorMsg(SubscribeID,reqUrl,"取消订阅信息对象，必要参数没有填写完整，请检查参数");
            }
        }catch (NullPointerException e){
            return Response.errorMsg(SubscribeID,reqUrl,"取消订阅信息对象，必要参数没有填写完整， 请检查参数");
        }
        s.setSubscribestatus("1");//已取消订阅
        try {
            //2.存在更新订阅消息（补充取消订阅说明）
            s.setUpdateBy(s.getApplicantname());
            s.setUpdateTime(DateUtils.getNowDate());
            int mark = subscribeMapper.updateSubscribe(s);
            if(mark>=1){
                return Response.ok(SubscribeID,reqUrl,"取消订阅成功");
            }else{
                return Response.ok(SubscribeID,reqUrl,"取消订阅失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.ok(SubscribeID,reqUrl,"取消订阅异常");
        }
    }

    /***
     * 删除订阅
     * @param IDList 键为IDList，值为用英文半角分号”,”分隔的字符串 ?IDList=330101020001032017113010580006371，330101020001032017113010580006372
     * @return
     */
    @Override
    public ResponseStatusListModeObject deleteSubscribeID(String IDList) {
        String reqUrl = "/VIID/Subscribes";
        List<ResponseStatus> resp3 = new ArrayList<ResponseStatus>();
        ResponseStatus r = new ResponseStatus();
        if(StringUtils.isEmpty(IDList)){
            r = Response.getResponError(IDList, reqUrl,"订阅id："+IDList+"传递异常,删除失败");
            resp3.add(r);
        }
        if(!IDList.contains(",")){
            IDList = IDList+",";
        }
        if(IDList.contains(",")){
            String[] ids = IDList.split(",");
            for(int i=0;i<ids.length;i++){
                String SubscribeID = ids[i];
                int mark = subscribeMapper.deleteSubscribeById("",SubscribeID);
                if(mark<=0){
                    r = Response.getResponError(SubscribeID,reqUrl,"订阅id："+SubscribeID+",删除异常，删除失败");
                    resp3.add(r);
                    continue;
                }else{
                    r = Response.getResponOk(SubscribeID,reqUrl,"订阅id："+SubscribeID+",删除成功");
                    resp3.add(r);
                }
            }
        }
        return Response.ok(resp3);
    }

    /**
     * 多条件查询订阅对象
     */
    @Override
    public SubscribeListObject querySubscribeID(String SubscribeID, String ApplicantName, String ApplicantOrg, String BeginTime, String EndTime, String Title,
                                                String SubscribeDetail, String ResourceClass, String ReportInterval,
                                                String Reason, String OperateType, String SubscribeStatus,
                                                String SubscribeCancelOrg, String SubscribeCancelPerson,
                                                String CancelTime, String CancelReson,
                                                String ResultImageDeclare, String ResultFeatureDeclare, String TabID) {
        SubscribeDB subscribe = new SubscribeDB();
        subscribe.setSubscribeid(SubscribeID!=null ? SubscribeID : "");
        subscribe.setApplicantname(ApplicantName!=null ? ApplicantName : "");
        subscribe.setApplicantorg(ApplicantOrg!=null ? ApplicantOrg : "");
        subscribe.setBegintime(BeginTime!=null ? BeginTime : "");
        subscribe.setEndTime(EndTime!=null ? EndTime : "");
        subscribe.setTitle(Title!=null ? Title : "");
        subscribe.setSubscribedetail(SubscribeDetail!=null ? SubscribeDetail:"");
        subscribe.setResourceclass(ResourceClass!=null ? ResourceClass : "");
        subscribe.setReportinterval(ReportInterval!=null ? ReportInterval:"");
        subscribe.setReason(Reason!=null ? Reason :"");
        subscribe.setOperatetype(OperateType!=null ? OperateType:"");
        subscribe.setSubscribestatus(SubscribeStatus!=null ?SubscribeStatus:"");
        subscribe.setSubscribecancelorg(SubscribeCancelOrg!=null?SubscribeCancelOrg:"");
        subscribe.setSubscribecancelperson(SubscribeCancelPerson!=null ? SubscribeCancelPerson:"");
        if(CancelTime!=null){
            //Date cancelTime = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS,CancelTime);
            subscribe.setCanceltime(CancelTime!=null ?CancelTime:"");
        }
        subscribe.setCancelreson(CancelReson!=null ? CancelReson:"");
        subscribe.setResultfeaturedeclare(ResultImageDeclare!=null ? ResultImageDeclare:"");
        subscribe.setResultfeaturedeclare(ResultFeatureDeclare!=null ? ResultFeatureDeclare:"");
        subscribe.setTabid(TabID!=null ? TabID : "");
        List<SubscribeDB> subscribeDBS = subscribeMapper.selectSubscribeList(subscribe);
        List<Subscribe> subscribes = new ArrayList<Subscribe>();
        if(subscribeDBS==null || subscribeDBS.size()<=0){
            return Response.okSubList(subscribes);
        }
        for(int i =0;i<subscribeDBS.size();i++){
            SubscribeDB sub = subscribeDBS.get(i);
            try {
                Subscribe conSub = (Subscribe) BenUtils.beanTobeanLowerCase2(sub, Subscribe.class);
                subscribes.add(conSub);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Response.okSubList(subscribes);
    }

    /**
     * 订阅任务修改
     * @param subscribeListObject
     * @return 消息体中SubscribeID必填，否则操作无效
     */
    @Override
    public ResponseStatusListModeObject updateSubscribeID(SubscribeListObject subscribeListObject) {
        String reqUrl = "/VIID/Subscribes";
        List<ResponseStatus> resp3 = new ArrayList<ResponseStatus>();
        ResponseStatus r = new ResponseStatus();
        String subscribeID = subscribeListObject.getSubscribeObject().getSubscribeList().get(0).getSubscribeID();
        if(subscribeListObject==null || StringUtils.isEmpty(subscribeID)){
            r = Response.getResponError(subscribeID, reqUrl,"参数订阅SubscribeID不能为空,修改失败");
            resp3.add(r);
        }
        List<Subscribe> subscribeList = subscribeListObject.getSubscribeObject().getSubscribeList();
        if(subscribeList==null || subscribeList.size()<=0){
            r = Response.getResponError(subscribeID, reqUrl,"修改订阅参数异常,修改失败");
            resp3.add(r);
        }
        for(int i=0;i<subscribeList.size();i++){
            Subscribe subscribe = subscribeList.get(i);
            try {
                SubscribeDB subscribeDB = (SubscribeDB)BenUtils.beanTobeanLowerCase(subscribe, SubscribeDB.class);
                subscribeDB.setUpdateBy(subscribeDB.getApplicantname());
                subscribeDB.setUpdateTime(DateUtils.getNowDate());
                int count = subscribeMapper.updateSubscribe(subscribeDB);
                if(count>=1){
                    r = Response.getResponOk(subscribeDB.getSubscribeid(),reqUrl,"订阅id："+subscribeDB.getSubscribeid()+",修改成功");
                    resp3.add(r);
                }
            } catch (Exception e) {
                log.error("复制SubscribeDB-Ben 异常：{}",e);
            }
        }
        return Response.ok(resp3);
    }
}
